﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Aliyun.Acs.Sms.Model.V20160927;
using Aliyun.MNS;
using Aliyun.MNS.Model;
using System.Collections.Generic;
using TY.UC.Common;
using TY.UC.Common.Extension;

namespace TY.UT.Message.AliMessage
{
    /// <summary>
    /// 阿里云短信
    /// </summary>
    public class AliMessageHelper
    {
        private static readonly string SignName = "SignName".GetStrValue();//管理控制台中配置的短信签名;
        private static readonly string SingleAccount =  "SingleAccount".GetStrValue();
        private static readonly string SinglePassword = "SinglePassword".GetStrValue();
        private static readonly string AliyunArea =  "AliyunArea".GetStrValue();
        private static readonly string MNSTopic = "MNSTopic".GetStrValue();//短信主题

        private static string product = "Dysmsapi";//短信API产品名称
        private static string domain = "dysmsapi.aliyuncs.com";//短信API产品域名

        /// <summary>
        /// 添加分店时，给分店负责人发送账号信息
        /// </summary>
        /// <param name="recNum">接收号码，多个号码可以逗号分隔</param>
        /// <param name="paramString">短信模板中的变量,json格式对象</param>
        /// <param name="templateCode">管理控制台中配置的审核通过的短信模板的模板CODE</param>
        /// <returns></returns>
        public static bool SendMessage(string recNum, string paramString, string templateCode)
        {
            SingleSendSmsRequest request = new SingleSendSmsRequest
            {
                SignName = SignName,
                TemplateCode = templateCode,
                RecNum = recNum,
                ParamString = paramString
            };
            try
            {
                SingleSendSmsResponse httpResponse = new DefaultAcsClient(DefaultProfile.GetProfile(AliyunArea, SingleAccount, SinglePassword)).GetAcsResponse(request);
                if (httpResponse.HttpResponse.Status == 200)
                {
                    return true;
                }
                LogHelper.WriteLog("AliMessageHelper","AliMessageHelper-SendMessage,Status=" + httpResponse.HttpResponse.Status + ",recNum=" + recNum + ",paramString=" + paramString + ",=templateCode=" + templateCode);
            }
            catch (ServerException ex)
            {
                LogHelper.WriteLog("AliMessageHelper", "AliMessageHelper-SendMessage,ServerException异常,recNum=" + recNum + ",paramString=" + paramString + ",=templateCode=" + templateCode, ex);
            }
            catch (ClientException ex)
            {
                LogHelper.WriteLog("AliMessageHelper", "AliMessageHelper-SendMessage,ClientException异常,recNum=" + recNum + ",paramString=" + paramString + ",=templateCode=" + templateCode, ex);
            }
            return false;
        }
        /// <summary>
        /// 阿里云发送短信
        /// 下载的sdk是2017-05-15的更新版本
        /// </summary>
        /// <param name="recNum">发送短信的手机号</param>
        /// <param name="param">参数配置，比如短信内容配置的参数名是valid_code，param的key是valid_code，value是变量值</param>
        /// <param name="templateCode">短信模板id</param>
        /// <returns></returns>
        public static bool SendMessage(string recNum, Dictionary<string, string> param, string templateCode)
        {
            try
            {
                IMNS client = new Aliyun.MNS.MNSClient(SingleAccount, SinglePassword, AliyunArea);
                 
                Topic topic = client.GetNativeTopic(MNSTopic);
                MessageAttributes messageAttributes = new MessageAttributes();
                BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
                batchSmsAttributes.FreeSignName = SignName;
                batchSmsAttributes.TemplateCode = templateCode;
                batchSmsAttributes.AddReceiver(recNum, param);
                messageAttributes.BatchSmsAttributes = batchSmsAttributes;
                PublishMessageRequest request = new PublishMessageRequest();
                request.MessageAttributes = messageAttributes;
                request.MessageBody = "smsmessage";

                PublishMessageResponse resq = topic.PublishMessage(request);
                LogHelper.WriteLog("AliMessageHelper-SendMessage,发短信返回结果：" + new { HttpStatusCode = (short)resq.HttpStatusCode });
                if ((short)resq.HttpStatusCode == 201 || (short)resq.HttpStatusCode == 200)
                {
                    return true;
                }
            }
            catch (ServerException ex)
            {
                LogHelper.WriteLog("AliMessageHelper-SendMessage,ServerException异常,recNum=" + recNum + ",paramString=" + param.JsonSe() + ",=templateCode=" + templateCode, ex);
                return false;
            }
            catch (ClientException ex)
            {
                LogHelper.WriteLog("AliMessageHelper-SendMessage,ClientException异常,recNum=" + recNum + ",paramString=" + param.JsonSe() + ",=templateCode=" + templateCode, ex);
                return false;
            }
            return false;
        }
        /// <summary>
        /// 阿里云发送短信
        /// 下载的sdk是2017-05-15的更新版本
        /// </summary>
        /// <param name="recNum">发送短信的手机号</param>
        /// <param name="param">参数配置，比如短信内容配置的参数名是valid_code，param的key是valid_code，value是变量值</param>
        /// <param name="templateCode">短信模板id</param>
        /// <returns></returns>
        public static bool SendMessageV2(string recNum, string param, string templateCode)
        {
            IClientProfile profile = DefaultProfile.GetProfile(AliyunArea, SingleAccount, SinglePassword); 

            DefaultProfile.AddEndpoint(AliyunArea, AliyunArea, product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = recNum;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = SignName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = templateCode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = param;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = System.Guid.NewGuid().ToString("N");
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                System.Console.WriteLine(sendSmsResponse.Message);


            }
            catch (ServerException e)
            { 
                return false;
            }
            catch (ClientException e)
            { 
                return false;
            }
            return true;
        }
    }
}
